import React, { useEffect, useRef, useState } from "react";
import { EnvironmentOutline } from "antd-mobile-icons";

// Define types for AMap objects
declare global {
  interface Window {
    AMap: any;
  }
}

interface Position {
  lng: number;
  lat: number;
}

interface GeocodeResult {
  info: string;
  regeocode: {
    formattedAddress: string;
  };
}

const DtAddress = () => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const mapInstance = useRef<any>(null);
  const [address, setAddress] = useState<string>("");
  const [position, setPosition] = useState<Position | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // 初始化地图
  useEffect(() => {
    initMap();
    return () => {
      if (mapInstance.current) {
        mapInstance.current.destroy();
      }
    };
  }, []);

  // 初始化高德地图
  const initMap = async () => {
    if (!window.AMap || !mapContainer.current) return;

    mapInstance.current = new window.AMap.Map(mapContainer.current, {
      center: [115.4889, 38.8149],
      resizeEnable: true,
      zoom: 16,
    });

    // 获取定位
    getLocationAndClockIn();
  };

  // 添加定位点标记
  const addMarker = (position: Position) => {
    const marker = new window.AMap.Marker({
      position: new window.AMap.LngLat(position.lng, position.lat),
      title: "当前位置",
    });
    mapInstance.current.add(marker);
  };

  // 获取定位并设置地址
  const getLocationAndClockIn = async () => {
    setIsLoading(true);
    try {
      // 获取定位
      const position = await getCurrentPosition();

      // 执行逆地理编码获取地址
      await reverseGeocode(position);

      // 添加标记
      addMarker(position);
    } catch (error: any) {
      const errorMsg =
        error.response?.data?.error || error.message || "定位失败";
      console.error(errorMsg);
    } finally {
      setIsLoading(false);
    }
  };

  // 获取当前位置
  const getCurrentPosition = (): Promise<Position> => {
    return new Promise((resolve, reject) => {
      window.AMap.plugin("AMap.Geolocation", () => {
        const geolocation = new window.AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
        });

        geolocation.getCurrentPosition((status: string, result: any) => {
          if (status === "complete") {
            setPosition(result.position);
            resolve(result.position);
          } else {
            reject(new Error(result.message));
          }
        });
      });
    });
  };

  // 监听位置变化执行逆地理编码
  useEffect(() => {
    if (position) {
      reverseGeocode(position);
    }
  }, [position]);

  // 逆地理编码功能 - 将坐标转换为地址
  const reverseGeocode = async (pos: Position): Promise<string> => {
    return new Promise((resolve) => {
      window.AMap.plugin("AMap.Geocoder", () => {
        const geocoder = new window.AMap.Geocoder({ city: "全国" });

        geocoder.getAddress([pos.lng, pos.lat], (status: string, result: GeocodeResult) => {
          if (status === "complete" && result.info === "OK") {
            const address =
              result.regeocode.formattedAddress.split("市")[0] + "市";
            if (!sessionStorage.getItem("address")) {
              setAddress(address);
              sessionStorage.setItem("address", address);
            }
            resolve(address);
          }
        });
      });
    });
  };

  return (
    <div style={{ padding: 0, margin: 0 }}>
      {/* 隐藏的地图容器 - 用于地图API初始化 */}
      <div
        ref={mapContainer}
        style={{
          width: "100%",
          height: "40vh",
          borderRadius: 8,
          overflow: "hidden",
          marginBottom: 12,
          display: "none",
        }}
      />

      {/* 位置信息显示 */}
      {position && (
        <div style={{ marginBottom: 12 }}>
          <p style={{ color: "#666", fontSize: 12 }}>
            <EnvironmentOutline />
            {sessionStorage.getItem("address")}
          </p>
        </div>
      )}
    </div>
  );
};

export default DtAddress;